const gameCanvas = document.getElementById('gameCanvas');
const nextCanvas = document.getElementById('nextCanvas');
const ctx = gameCanvas.getContext('2d');
const nextCtx = nextCanvas.getContext('2d');
const scoreElement = document.getElementById('score');
const timeElement = document.getElementById('time');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');

const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const NEXT_BLOCK_SIZE = 20;

let board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
let score = 0;
let time = 0;
let timerId;
let fallingPiece;
let nextPiece;
let gameLoop;
let isPaused = false;

const SHAPES = [
	[
		[1, 1, 1, 1]
	],
	[
		[1, 1],
		[1, 1]
	],
	[
		[1, 1, 1],
		[0, 1, 0]
	],
	[
		[1, 1, 1],
		[1, 0, 0]
	],
	[
		[1, 1, 1],
		[0, 0, 1]
	],
	[
		[1, 1, 0],
		[0, 1, 1]
	],
	[
		[0, 1, 1],
		[1, 1, 0]
	]
];

const COLORS = [
	'#00FFFF', '#FFFF00', '#800080', '#FF0000', '#0000FF', '#00FF00', '#FFA500'
];

function drawBlock(x, y, color, ctx, blockSize) {
	ctx.fillStyle = color;
	ctx.fillRect(x * blockSize, y * blockSize, blockSize, blockSize);
	ctx.strokeStyle = 'black';
	ctx.strokeRect(x * blockSize, y * blockSize, blockSize, blockSize);
}

function drawBoard() {
	for (let y = 0; y < ROWS; y++) {
		for (let x = 0; x < COLS; x++) {
			if (board[y][x]) {
				drawBlock(x, y, COLORS[board[y][x] - 1], ctx, BLOCK_SIZE);
			}
		}
	}
}

function drawPiece(piece, offsetX, offsetY, ctx, blockSize) {
	piece.shape.forEach((row, y) => {
		row.forEach((value, x) => {
			if (value) {
				drawBlock(x + offsetX, y + offsetY, COLORS[piece.color], ctx, blockSize);
			}
		});
	});
}

function drawNextPiece() {
	nextCtx.clearRect(0, 0, nextCanvas.width, nextCanvas.height);
	const offsetX = (nextCanvas.width / NEXT_BLOCK_SIZE - nextPiece.shape[0].length) / 2;
	const offsetY = (nextCanvas.height / NEXT_BLOCK_SIZE - nextPiece.shape.length) / 2;
	drawPiece(nextPiece, offsetX, offsetY, nextCtx, NEXT_BLOCK_SIZE);
}

function createPiece() {
	const shapeIndex = Math.floor(Math.random() * SHAPES.length);
	return {
		shape: SHAPES[shapeIndex],
		color: shapeIndex,
		x: Math.floor((COLS - SHAPES[shapeIndex][0].length) / 2),
		y: 0
	};
}

function collides(piece, x, y) {
	for (let row = 0; row < piece.shape.length; row++) {
		for (let col = 0; col < piece.shape[row].length; col++) {
			if (piece.shape[row][col] &&
				(board[y + row] && board[y + row][x + col]) !== 0) {
				return true;
			}
		}
	}
	return false;
}

function rotate(piece) {
	const newShape = piece.shape[0].map((_, i) =>
		piece.shape.map(row => row[i]).reverse()
	);
	if (!collides({
			...piece,
			shape: newShape
		}, piece.x, piece.y)) {
		piece.shape = newShape;
	}
}

function dropPiece() {
	fallingPiece.y++;
	if (collides(fallingPiece, fallingPiece.x, fallingPiece.y)) {
		fallingPiece.y--;
		mergePiece();
		clearLines();
		if (fallingPiece.y === 0) {
			gameOver();
			return;
		}
		fallingPiece = nextPiece;
		nextPiece = createPiece();
		drawNextPiece();
	}
}

function mergePiece() {
	fallingPiece.shape.forEach((row, y) => {
		row.forEach((value, x) => {
			if (value) {
				board[y + fallingPiece.y][x + fallingPiece.x] = fallingPiece.color + 1;
			}
		});
	});
}

function clearLines() {
	let linesCleared = 0;
	for (let y = ROWS - 1; y >= 0; y--) {
		if (board[y].every(cell => cell !== 0)) {
			board.splice(y, 1);
			board.unshift(Array(COLS).fill(0));
			linesCleared++;
			y++;
		}
	}
	if (linesCleared > 0) {
		score += linesCleared * 100;
		scoreElement.textContent = `分数: ${score}`;
	}
}

function movePiece(dx) {
	if (!collides(fallingPiece, fallingPiece.x + dx, fallingPiece.y)) {
		fallingPiece.x += dx;
	}
}

function gameOver() {
	clearInterval(gameLoop);
	clearInterval(timerId);
	ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
	ctx.fillRect(0, 0, gameCanvas.width, gameCanvas.height);
	ctx.fillStyle = 'white';
	ctx.font = '30px Arial';
	ctx.textAlign = 'center';
	ctx.fillText('游戏结束', gameCanvas.width / 2, gameCanvas.height / 2);
	startBtn.textContent = '重新开始';
	startBtn.style.display = 'block';
	pauseBtn.style.display = 'none';
}

function updateTime() {
	time++;
	const minutes = Math.floor(time / 60).toString().padStart(2, '0');
	const seconds = (time % 60).toString().padStart(2, '0');
	timeElement.textContent = `时间: ${minutes}:${seconds}`;
}

function draw() {
	ctx.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
	drawBoard();
	drawPiece(fallingPiece, fallingPiece.x, fallingPiece.y, ctx, BLOCK_SIZE);
}

function gameStart() {
	board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
	score = 0;
	time = 0;
	scoreElement.textContent = '分数: 0';
	timeElement.textContent = '时间: 00:00';
	fallingPiece = createPiece();
	nextPiece = createPiece();
	drawNextPiece();

	if (gameLoop) clearInterval(gameLoop);
	if (timerId) clearInterval(timerId);

	gameLoop = setInterval(() => {
		if (!isPaused) {
			dropPiece();
			draw();
		}
	}, 500);

	timerId = setInterval(() => {
		if (!isPaused) {
			updateTime();
		}
	}, 1000);

	startBtn.textContent = '重新开始';
	pauseBtn.style.display = 'block';
	isPaused = false;
}

function togglePause() {

	if (gameLoop) {
		isPaused = !isPaused;
		pauseBtn.textContent = isPaused ? '继续' : '暂停';
	}
}

startBtn.addEventListener('click', gameStart);

pauseBtn.addEventListener('click', togglePause);

document.addEventListener('keydown', (e) => {
	if (e.key === ' ') {
		if (gameLoop) {
			togglePause();
		}
		e.preventDefault();
	} else if (!isPaused && gameLoop) {
		switch (e.key) {
			case 'ArrowLeft':
				movePiece(-1);
				break;
			case 'ArrowRight':
				movePiece(1);
				break;
			case 'ArrowDown':
				dropPiece();
				break;
			case 'ArrowUp':
				rotate(fallingPiece);
				break;
		}
		draw();
	}
});

draw();